<?php

namespace app\common\service;

use app\common\exception\Client;
use app\common\model\User as UserModel;
use app\common\model\UserAddress as UserAddressModel;
use app\common\service\User as UserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserAddress
{
    /**
     * 保存用户地址
     * @param array $data
     * @param $token
     * @return array
     * @throws Client
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function saveUserAddress(array $data,$token): array
    {
        $userId = (new UserService())->getUserIdFromToken($token);
        $user = UserModel::find($userId);
        if(!$user){throw new Client(223001,'非法token用户不存在');}

        $data['comunum'] = 1;
        $userAddress = UserAddressModel::where('user_id',$userId)->find();
        if($userAddress) {
            //更新
            $userAddress->save($data);
            return $userAddress->toArray();
        }
        //新增
        $data['user_id'] = $userId;
        $userAddress = new UserAddressModel();
        $userAddress->save($data);
        return $userAddress->toArray();
    }

    /**
     * 获取用户地址
     * @param $token
     * @return array
     * @throws Client
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getUserAddress($token): array
    {
        $userId = (new UserService())->getUserIdFromToken($token);
        $user = UserModel::find($userId);
        if(!$user){throw new Client(223001,'用户不存在');}

        $userAddress = UserAddressModel::where('user_id',$userId)->find();
        if (!$userAddress) {
            throw new Client(223001,'用户地址不存在');
        }
        if($userAddress->comunum==1){$userAddress->detail;}
        return $userAddress->toArray();
    }


}